import React, { useEffect, useState } from 'react'
import classNames from 'classnames'
import { Button, Card, Collapse, Descriptions, message, Select, Space } from 'antd'
import Icon, { AreaChartOutlined, EditOutlined, EnvironmentOutlined, TruckOutlined } from '@ant-design/icons'

import {
  apiGetWarehouseList,
  apiGetWaybillDestinationAddress,
  apiGetWaybillOriginAddress,
  apiGetWaybillTransferWarehouseInformation,
  apiSetWarehouse,
} from '../../apis'
import { WarehouseODTO } from '../../interface'
import { useUrlParams } from '../../utils'
import warehouseOutlined from '@/assets/icons/warehouseOutlined.svg?react'
import styles from './styles.module.less'

const CollapseContent = ({ item, success }: { item: WarehouseODTO; success: () => void }) => {
  const { waybillNo } = useUrlParams()
  const [activeKey, setActiveKey] = useState<string[]>([])
  const [editable, setEditable] = useState(false)
  const [warehouseOptions, setWarehouseOptions] = useState<{ label: string; value: string }[]>([])
  const [loading, setLoading] = useState(false)

  const getWarehouseOptions = async () => {
    try {
      setLoading(true)
      const res = await apiGetWarehouseList({
        warehouseType: item.warehouseType,
      })
      setWarehouseOptions(
        res.map(item => ({
          label: item.warehouseName || '',
          value: item.warehouseId || '',
        })),
      )
    } finally {
      setLoading(false)
    }
  }

  const editableHandle = () => {
    setEditable(true)
    getWarehouseOptions()
    setActiveKey([])
  }

  const warehouseChangeHandle = async (value: string) => {
    try {
      setLoading(true)
      await apiSetWarehouse({
        waybillNo,
        warehouseId: value,
        warehouseType: item.warehouseType,
      })
      message.success('更新成功')
      setEditable(false)
      success()
    } finally {
      setLoading(false)
    }
  }

  const iconList = (warehouseType?: number) => {
    switch (warehouseType) {
      case 0:
        return <AreaChartOutlined className={styles.warehouseIcon} />
      case 1:
        return <Icon component={warehouseOutlined} className={styles.warehouseIcon} />
      case 2:
        return <TruckOutlined className={styles.warehouseIcon} />
      case 3:
        return <EnvironmentOutlined className={styles.warehouseIcon} />
      default:
        return null
    }
  }

  return (
    <Collapse
      className={styles.warehouseCollapse}
      collapsible="icon"
      expandIconPosition="end"
      activeKey={activeKey}
      expandIcon={editable ? () => <React.Fragment /> : undefined}
      onChange={setActiveKey}
      items={[
        {
          key: '1',
          label: (
            <div className={styles.warehouse_content}>
              <div className={styles.warehouse_content_left}>
                {iconList(item.warehouseType)}
                {editable ? (
                  <Space>
                    <Select
                      loading={loading}
                      style={{ width: 200 }}
                      options={warehouseOptions}
                      onChange={warehouseChangeHandle}
                    />
                    <Button size="small" onClick={() => setEditable(false)}>
                      取消
                    </Button>
                  </Space>
                ) : (
                  <div>
                    <div className={styles.warehouseName}>{item.warehouseName}</div>
                    <div className={classNames('small_print', styles.warehouseAddress)}>{item.address}</div>
                  </div>
                )}
              </div>
              {!editable && (
                <div className={styles.warehouse_content_right}>
                  {[1, 2].includes(item.warehouseType as number) && (
                    <Button
                      icon={<EditOutlined className={styles.warehouseEditIcon} />}
                      type="link"
                      onClick={editableHandle}
                    />
                  )}
                </div>
              )}
            </div>
          ),
          children: (
            <Descriptions
              layout="vertical"
              size="small"
              column={2}
              items={[
                {
                  label: '联系人',
                  children: item.person || '',
                },
                {
                  label: '电话',
                  children: item.phone || '',
                },
                {
                  label: '邮箱',
                  children: item.email || '',
                },
              ]}
            />
          ),
        },
      ]}
    />
  )
}

export const WarehouseInfo = () => {
  const { waybillNo } = useUrlParams()
  const [warehouseInfo, setWarehouseInfo] = useState<WarehouseODTO[]>()

  const getWarehouseInfo = async () => {
    const originRes = await apiGetWaybillOriginAddress({
      waybillNo,
    })
    const destinationRes = await apiGetWaybillDestinationAddress({
      waybillNo,
    })
    const transferRes = await apiGetWaybillTransferWarehouseInformation({
      waybillNo,
    })
    setWarehouseInfo([
      {
        ...originRes,
        warehouseName: originRes.chineseName || originRes.englishName || '',
        address: `${originRes.stateProvince}${originRes.city}${originRes.street1}`,
        warehouseType: 0,
        warehouseId: `origin_${originRes.addressId}`,
      },
      ...(transferRes.warehouseODTOS || []),
      {
        ...destinationRes,
        warehouseName: destinationRes.chineseName || destinationRes.englishName || '',
        address: `${destinationRes.stateProvince}${destinationRes.city}${destinationRes.street1}`,
        warehouseType: 3,
        warehouseId: `destination_${destinationRes.addressId}`,
      },
    ])
  }

  useEffect(() => {
    getWarehouseInfo()
  }, [])

  return (
    <Card>
      {warehouseInfo?.map(item => (
        <div className={styles.warehouseInfo} key={item.warehouseId}>
          <CollapseContent item={item} success={getWarehouseInfo} />
        </div>
      ))}
    </Card>
  )
}
